﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SalePartial.BLL;
using SalePartial.BLL.SAServiceRef;
using System.Data;
using Telerik.Web.UI;
using System.Drawing;
using System.Text.RegularExpressions;
using System.IO;

public partial class SAClientWeb_FamilyDownFrm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Guid familyId;
            if (HttpContext.Current.Session["familyId"] != null)
            {
                familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

                FamilyDownFrm_Load(familyId);
            }
            else
            {
                SABLL.ShowInfoMsg(this, @"无法下载，请在零件列表中至少选中一个零件！");
                return;
            }

        }
    }

    private void FamilyDownFrm_Load(Guid familyId)
    {
        //get data.
        FamilyInfo m_familyInfo = SABLL.GetFamilyInfo(familyId);
        this.Title = "零件下载--" + m_familyInfo.DisplayName;

         List<ParameterInfo> m_keyParameters = SABLL.GetFamilyKeyParameters(m_familyInfo.ID);
        if (m_keyParameters == null)
        {
            SABLL.ShowErrMsg(this,SABLL.GetLastErrMsg());
            return;
        }

        List<ParameterInfo> m_nonCustomKeyParameters = new List<ParameterInfo>();
        List<ParameterInfo> m_customKeyParameters = new List<ParameterInfo>();

        foreach (ParameterInfo item in m_keyParameters)
        {
            if (item.IsCustom)
            {
                m_customKeyParameters.Add(item);
            }
            else
            {
                m_nonCustomKeyParameters.Add(item);
            }
        }

        InitListViewForNonCustomKeyParameters(m_nonCustomKeyParameters);
        InitTextBoxForCustomKeyParameters(m_customKeyParameters);

        //init model, drawing pictures.
        //get data.
        FamilyAttrInfo familyAttr = SABLL.GetFamilyAttrInfo(m_familyInfo.ID);

        if (familyAttr == null)
        {
            SABLL.ShowErrMsg(this,SABLL.GetLastErrMsg());
            return;
        }

        this.pictureBox_ModelPic.DataValue = familyAttr.ModelPicBinary;
        this.pictureBox_DrawingPic.DataValue = familyAttr.DrawPicBinary;

    }

    private void InitListViewForNonCustomKeyParameters(List<ParameterInfo> m_parameters)
    {
        listBox_NonCustomParamList1.DataSource = m_parameters;
        listBox_NonCustomParamList1.DataBind();
    }

    protected void listBox_NonCustomParamList1_ItemDataBound(object sender, RadListViewItemEventArgs e)
    {
        //if (!Page.IsPostBack)
        //{
        //    if (e.Item.ItemType == RadListViewItemType.DataItem)
        //    {
        //        RadComboBox ddl = e.Item.FindControl("ddl") as RadComboBox;
        //        //ddl.SelectedIndexChanged += new RadComboBoxSelectedIndexChangedEventHandler(ddl_SelectedIndexChanged);

        //        var lvItem = ((RadListViewDataItem)e.Item);
        //        Guid ID = new Guid(lvItem.GetDataKeyValue("ID").ToString());
        
        //        List<ParameterValueInfo> emptyConstraint = new List<ParameterValueInfo>();
        //        List<ParameterValueInfo> retVals = SABLL.GetParamVals(ID, emptyConstraint);

        //        if (retVals == null)
        //        {
        //            SABLL.ShowErrMsg(this,SABLL.GetLastErrMsg());
        //            return;
        //        }

        //        ddl.DataSource = retVals;
        //        ddl.DataTextField = "Value";
        //        ddl.DataValueField = "ID";
        //        ddl.DataBind();

        //    }
        //}
    }

    protected void ddl_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
    {
        List<ParameterValueInfo> emptyConstraint = new List<ParameterValueInfo>();

        foreach (RadListViewDataItem dataitem in listBox_NonCustomParamList1.Items)
        {
            RadComboBox ddl = dataitem.FindControl("ddl") as RadComboBox;
            if (ddl != null && ddl == (RadComboBox)sender)
            {
                Guid ID = new Guid(dataitem.GetDataKeyValue("ID").ToString());

                List<ParameterValueInfo> retVals = SABLL.GetParamVals(ID, emptyConstraint);

                if (retVals == null)
                {
                    SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
                    return;
                }

                ddl.DataSource = retVals;
                ddl.DataTextField = "Value";
                ddl.DataValueField = "ID";
                ddl.DataBind();

                if (retVals.Count > 0)
                {
                    ddl.SelectedIndex = 0;
                }
                return;
            }
            else if (ddl != null && ddl.SelectedValue!=string.Empty)
            {
                ParameterValueInfo info = new ParameterValueInfo();
                info.ID = new Guid(ddl.SelectedValue);
                info.Value = ddl.Text;
                emptyConstraint.Add(info);
            }
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        ViewState["ID"] = ((RadComboBox)sender).SelectedValue;
    }


    
    private void InitTextBoxForCustomKeyParameters(List<ParameterInfo> m_parameters)
    {
        foreach (ParameterInfo item in m_parameters)
        {
            //set parameter title.
            if (item.IsCustom)
            {
                double lowLimit, upLimit;
                bool success = SABLL.GetLimits(item.Tag, out lowLimit, out upLimit);
                if (success)
                {
                    item.DisplayName = String.Format("{0}[{1}-{2}]", item.DisplayName, lowLimit, upLimit);
                }
                else
                {
                    
                    //newLabel.Text = item.DisplayName;
                }

                //set text default value.
                double dDefault;
                if (SABLL.GetDefault(item.Tag, out dDefault))
                {
                    item.Value = Convert.ToString(dDefault);
                }

                //add text change event.
                //double lowLimit, upLimit;
                //if (SABLL.GetLimits(item.Tag, out lowLimit, out upLimit))
                //{
                //    newTextBox.TextChanged += new EventHandler(newTextBox_TextChanged);
                //}

            }
            else
            {
                //newLabel.Text = item.DisplayName;
            }

        }
        listBox_CustomParamList1.DataSource = m_parameters;
        listBox_CustomParamList1.DataBind();
    }
    

    protected void tabControl_Click(object sender, RadTabStripEventArgs e)
    {
        if (((RadTabStrip)sender).SelectedTab.PageViewID == tabPage_FamilyTable.ID)
        {
            DataTable dt = this.GetDataTableByUserDriverParameterSelection();
            
            InitSubFamilyTableGridView(dt);
            
            if (this.dataGridView_subFamilyTable.Items.Count > 0)
            {
                //this.dataGridView_subFamilyTable.Rows[0].Selected = true;
            }
        }

        //if (m_dictListBoxStart2End.Count > 0)
        //{
        //   ViewState["m_bListViewSelectionChanged"] = false;
        //}
    }


    private void InitSubFamilyTableGridView(DataTable dt)
    {

        if (dataGridView_subFamilyTable.Columns.Count > 0)
        {
            dataGridView_subFamilyTable.Columns.Clear();
        }
        dataGridView_subFamilyTable.AutoGenerateColumns = false;

        //
        //this.dataGridView_subFamilyTable.ReadOnly = false;
        //this.dataGridView_subFamilyTable.AllowUserToAddRows = true;
        //this.dataGridView_subFamilyTable.AllowUserToDeleteRows = true;
        Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);

        int cnt = dt.Columns.Count;
        for (int i = 0; i < cnt; i++)
        {
           //GridColumn curCol = this.dataGridView_subFamilyTable.Columns[i];
           string parameterGuid = dt.Columns[i].ColumnName;
           if (parameterGuid == null || !isGuid.IsMatch(parameterGuid))
           {
               
           }
           else
           {
               try
               {
                   //curCol.Tag = parameterGuid;

                   ParameterInfo paramInfo = SABLL.GetFamilyParameterInfo(new Guid(parameterGuid));
                   if (paramInfo != null)
                   {
                       dt.Columns[i].ColumnName = paramInfo.DisplayName;
                       //curCol.Tag = paramInfo;
                   }
               }
               catch (Exception)
               {

               }
           }

            GridBoundColumn boundColumn = new GridBoundColumn();
            //boundColumn.UniqueName = dt.Columns[i].ColumnName.Replace(" ","");
            boundColumn.DataField = dt.Columns[i].ColumnName;
            boundColumn.HeaderText = dt.Columns[i].ColumnName;
            if (i == 0 || i == 1)
            {
                boundColumn.Visible = false;
            }

            dataGridView_subFamilyTable.Columns.Add(boundColumn);
        }
        //if (cnt > 0)
        //{
        //    dt.Columns.RemoveAt(0);
        //    dt.Columns.RemoveAt(0);

        //    //this.dataGridView_subFamilyTable.Columns[0].Visible = false;
        //    //this.dataGridView_subFamilyTable.Columns[1].Visible = false;
        //}

        this.dataGridView_subFamilyTable.DataSource = dt;
        this.dataGridView_subFamilyTable.DataBind();
        //this.dataGridView_subFamilyTable.AllowUserToAddRows = false;
        //this.dataGridView_subFamilyTable.AllowUserToDeleteRows = false;
        //this.dataGridView_subFamilyTable.ReadOnly = true;
    }


    //protected void listBox_CustomParamList_ItemDataBound(object sender, GridItemEventArgs e)
    //{

    //    if (e.Item is GridDataItem)
    //    {

    //        GridDataItem itm = (GridDataItem)e.Item;

    //        //bool IsDriver = (bool)itm.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsDriver"];
    //        bool IsDriver = true;

    //        TableCell cellCust = (TableCell)itm["IsCustom"];
    //        TableCell cellDri = (TableCell)itm["IsDriver"];

    //        bool.TryParse(cellDri.Text, out IsDriver);

    //        if (!IsDriver)
    //        {
    //            //  cell.Text = false;
    //            cellCust.Enabled = true;
    //            cellCust.BackColor = Color.LightGray;

    //            cellDri.Enabled = true;
    //            cellDri.BackColor = cellCust.BackColor;
    //        }
    //        else
    //        {
    //            TableCell cellName = (TableCell)itm["Name"];
    //            cellName.Font.Bold = true;
    //            cellName.ForeColor = Color.Red;
    //            //cellCust.Value = curKeyParam.IsCustom;
    //            cellCust.Enabled = false;
    //            cellDri.Enabled = false;
    //        }
    //    }
    //}

    private DataTable GetDataTableByUserDriverParameterSelection()
    {
        Guid familyId;
        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

        }
        else
        {
            return null;
        }
       
        List<ParameterValueInfo> paramConstraints = this.GetParameterConstrains();

        DataTable dt = SABLL.GetSubFamilyTable(familyId, paramConstraints);

        if (dt == null)
        {
            SABLL.ShowInfoMsg(this,SABLL.GetLastErrMsg());
        }
        return dt;
    }

    private List<ParameterValueInfo> GetParameterConstrains()
    {
        List<ParameterValueInfo> retList = new List<ParameterValueInfo>();

        //if (listBox == null)
        //{
        //    return retList;
        //}

        foreach (RadListViewDataItem dataitem in listBox_NonCustomParamList1.Items)
        {
            RadComboBox ddl = dataitem.FindControl("ddl") as RadComboBox;
            //if (ddl.SelectedValue == ViewState["ID"])
            //{
                ParameterValueInfo newInfo = new ParameterValueInfo();

                newInfo.ID = new Guid(dataitem.GetDataKeyValue("ID").ToString());
                newInfo.Value = ddl.Text;
                retList.Add(newInfo);
                //break;
            //}
        }

        return retList;
    }
    protected void button_close_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
    }

    protected void button_downLoad_Click(object sender, EventArgs e)
    {
        if (tabControl_parameterSelection.SelectedIndex == 1)
        {
            if (this.tabControl_parameterSelection.SelectedTab.PageViewID == tabPage_ParamSelection.ID)
            {

                DataTable dt = this.GetDataTableByUserDriverParameterSelection();
                if (dt == null) return;
                if (dt.Rows.Count > 1)
                {
                    SABLL.ShowInfoMsg(this, "结果有多项，请在[参数明细]中继续选择，默认选择第一组数据！");
                    this.tabControl_parameterSelection.SelectedIndex = 1;
                    tabPage_FamilyTable.Selected = true;
                    this.button_downLoad.Enabled = true;
                    return;
                }
                else if (dt.Rows.Count == 1)
                {
                    tabPage_FamilyTable.Selected = true;
                }
            }
            StartDownLoad();
        }
        else
        {

            List<ParameterValueInfo> retList = new List<ParameterValueInfo>();
            foreach (RadListViewDataItem dataitem in listBox_NonCustomParamList1.Items)
            {
                RadComboBox ddl = dataitem.FindControl("ddl") as RadComboBox;
                if (ddl.Text == "")
                {
                    SABLL.ShowInfoMsg(this, "请确保驱动参数的数据完整！");
                    this.tabControl_parameterSelection.SelectedIndex = -1;
                    tabPage_ParamSelection.Selected = true;
                    this.button_downLoad.Enabled = true;
                    
                    return;
                }
                else 
                {
                    tabPage_FamilyTable.Selected = true;
                    tabControl_parameterSelection.SelectedIndex = 1;

                    if (tabPage_FamilyTable.ID == "tabPage_FamilyTable")
                    {
                    
                        DataTable dt = this.GetDataTableByUserDriverParameterSelection();

                        InitSubFamilyTableGridView(dt);

                        if (this.dataGridView_subFamilyTable.Items.Count > 0)
                        {
                            //this.dataGridView_subFamilyTable.Rows[0].Selected = true;
                        }
                    }

                }

            }
        }

        
            
   }

    private void StartDownLoad()
    {
       GridItemCollection gicol = dataGridView_subFamilyTable.SelectedItems;

       Guid instanceId = Guid.Empty;
       string fileName = string.Empty;
       if (gicol == null || gicol.Count > 0)
       {
           try
           {
               instanceId = new Guid(gicol[0].Cells[2].Text);
               fileName = gicol[0].Cells[4].Text;
           }
           catch (Exception)
           {
           }
           //for(int i=0;i<dataGridView_subFamilyTable.Columns.Count;i++)
           //{
           //    if(dataGridView_subFamilyTable.Columns[i].HeaderText.Trim() == "File Name")
           //    {
           //        fileName = gicol[0].Cells[i].Text;
           //    }
           //    else if (dataGridView_subFamilyTable.Columns[i].HeaderText.Trim() == "instanceID")
           //    {
           //        instanceId = new Guid(gicol[0].Cells[i].Text);
           //    }
           //}
           
       }

       Guid familyId = Guid.Empty;

       if (HttpContext.Current.Session["familyId"] != null)
       {
           familyId =new Guid( HttpContext.Current.Session["familyId"].ToString());
       }
       List<ParameterValueInfo> driveParameterVals = SABLL.GetDriveParameterVals(familyId, instanceId);
       if (driveParameterVals == null)
       {
           SABLL.ShowErrMsg(this,SABLL.GetLastErrMsg());
           return;
       }

       List<ParameterValueInfo> customParameterVals = this.GetAllCustomParameterVals();
       if (customParameterVals == null) return;

       bool success = ApplyCustomDriveParameters(ref driveParameterVals, customParameterVals);
       if (!success) return;

       List<ParameterInfo> driveParameterInfos = new List<ParameterInfo>();

       for (int i = 0; i < driveParameterVals.Count; i++)
       {
           ParameterInfo newParamInfo = SABLL.GetFamilyParameterInfo(driveParameterVals[i].ID);
           newParamInfo.Value = driveParameterVals[i].Value;
           driveParameterInfos.Add(newParamInfo);
       }

       //
       //show download frm, get the target path and file type.
       FamilyAttrInfo tempAttr = SABLL.GetFamilyAttrInfo(familyId);

        if(fileName == string.Empty)
        {
            fileName = tempAttr.ReferenceName;
        }

       string targetPath = String.Empty;

       //?????????????????????????
       targetPath = Path.Combine(@"C:\", fileName + "."+comboBox_filetype.Text);

       //string radalertscript = "<script language='javascript'>function f(){var win = window.radopen('DownLoadFrm.aspx','Details');win.setSize(600, 300); win.center(); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);</script>";
       //Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);

       success = SABLL.GeneratePart(this,familyId, instanceId, driveParameterInfos, targetPath);
       
       if (!success)
       {
           SABLL.ShowErrMsg(this,SABLL.GetLastErrMsg());
           return;
       }
       //else if (success)
       //{
       //    SABLL.ShowInfoMsg(this,"下载成功：" + targetPath);
       //    return;
       //}

    }

    private bool ApplyCustomDriveParameters(ref List<ParameterValueInfo> driveParameterVals, List<ParameterValueInfo> customParameterVals)
    {
        foreach (ParameterValueInfo customParamVal in customParameterVals)
        {
            foreach (ParameterValueInfo driveParamVal in driveParameterVals)
            {
                if (driveParamVal.ID == customParamVal.ID)
                {
                    driveParamVal.Value = customParamVal.Value;
                    break;
                }
            }
        }
        return true;
    }

    private List<ParameterValueInfo> GetAllCustomParameterVals()
    {
        List<ParameterValueInfo> retList = new List<ParameterValueInfo>();
        string id = null;
        for (int i=0; i<listBox_CustomParamList1.Items.Count;i++)
        {
             ParameterValueInfo retInfo = new ParameterValueInfo();

             id = listBox_CustomParamList1.DataKeys[i].Value.ToString();
             TextBox txtBox = (TextBox)listBox_CustomParamList1.Items[i].FindControl("Label1");

            if (id == null)
            {
                SABLL.ShowErrMsg(this,"自定义参数数据丢失，请重新打开下载窗口！");
                return null;
            }
            if (txtBox.ForeColor == Color.Red) //incorrect data. return.
            {
                SABLL.ShowErrMsg(this, String.Format("自定义参数 [{0}] 的值 [{1}] 无效，请重新设置！", id, txtBox.Text));
                return null;
            }

           
            retInfo.ID = new Guid(id);
            retInfo.Value = txtBox.Text.Trim();
            retList.Add(retInfo);
        }

        return retList;
    }

    protected void LbtnLink_Click(object sender, EventArgs e)
    {
    }
    
    protected void button_downDoc_Click(object sender, EventArgs e)
    {
        Guid familyId;
        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

        }
        else
        {
            SABLL.ShowInfoMsg(this, @"无法下载，请在零件列表中至少选中一个零件！");
            return ;
        }
        FamilyAttrInfo familyAttrInfo = SABLL.GetFamilyAttrInfoByType(familyId,
            FamilyAttrType.kReference);

        if (familyAttrInfo != null && !String.IsNullOrEmpty(familyAttrInfo.ReferenceName) &&
            familyAttrInfo.ReferenceBinary != null && familyAttrInfo.ReferenceBinary.Length > 0)
        {
            try
            {
                //远程下载文件 小文件
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + familyAttrInfo.ReferenceName);
                HttpContext.Current.Response.BinaryWrite(familyAttrInfo.ReferenceBinary);
                Response.Flush();
                Response.Close();
            }
            catch (Exception)
            {
            }
            //SABLL.ShowInfoMsg(this, String.Format("保存文档成功！"));
        }
        else
        {
            //no referece document.
            SABLL.ShowInfoMsg(this, @"无可下载的文档资料！");
        }
    }
    
    
}